package com.ranga.mselfcare ;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.ranga.mselfcare.config.Config;
import com.ranga.mselfcare.entity.Transaction;
import com.ranga.mselfcare.services.TransactionService;

@SuppressLint("HandlerLeak")
public class TransactionActivity extends Activity {
	private ProgressDialog progressDialog;
	private int status = Config.PROGRESS_STOPPED;
	private final String TAG = "TransactionActivity";
	private String token = "";
	private String phoneNumber = "";
	private ListView lViewTransactionHistory;
	private final String TOP_UP_TRANSACTION = "TopUpTransactions";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_transaction);
		
		initializeDataFromSharedPreference();
		lViewTransactionHistory = (ListView) findViewById(R.id.lvTransactionHistory);
		progressDialog = new ProgressDialog(this);
		
		
		
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		hideProgressDialog();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (status == Config.PROGRESS_STARTED) {
			progressDialog.setMessage(this.getString(R.string.getting_balance));
			progressDialog.show();
		}
		if (status == Config.PROGRESS_STOPPED) {
			getTransactionDetails();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Config.STATUS, status);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		status = savedInstanceState.getInt(Config.STATUS);
	}
	
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		boolean networkAvailable = false;

		if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
			networkAvailable = true;
		} else {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setTitle(getString(R.string.alert));
			alertDialog
					.setMessage(getString(R.string.no_internet_connectivity));
			alertDialog.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(
									WifiManager.ACTION_PICK_WIFI_NETWORK));
						}
					});
			alertDialog.show();
		}
		return networkAvailable;
	}
	
	private Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {

			status = message.arg1;

			switch (status) {

			case Config.PROGRESS_STARTED:
				Log.i(TAG, "Progress Started");
				progressDialog.setMessage(TransactionActivity.this
						.getString(R.string.getting_transaction));
				progressDialog.show();
				break;
			case Config.PROGRESS_STOPPED:
				Log.i(TAG, "Progress stopped");
				hideProgressDialog();
				status = Config.PROGRESS_STOPPED;
				Toast.makeText(TransactionActivity.this, "Error getting Transaction!",
						Toast.LENGTH_SHORT).show();
				break;
			case Config.PROGRESS_SUCCESS:
				Log.i(TAG, "Progress success");
				status = Config.PROGRESS_STOPPED;
				hideProgressDialog();
				break;
			}
		};
	};

	private Handler serviceResultHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle resultBundle = message.getData();
			int errorCode = 0;
			String response = null;
			
			if (resultBundle.containsKey(Config.RESPONSE_ERROR)) {
				errorCode = Integer.parseInt(resultBundle.getString(Config.RESPONSE_ERROR));
			}
			if (resultBundle.containsKey(Config.RESPONSE)) {
				response = resultBundle.getString(Config.RESPONSE);
			}
			if (errorCode == 200) {
				if (resultBundle.containsKey(Config.RESPONSE)) {
					ArrayList<Transaction> transactionList = parseJsonList(response);
					TransactionListAdapter adapter = new TransactionListAdapter(transactionList, TransactionActivity.this);
					lViewTransactionHistory.setAdapter(adapter);
				}
			} else if (errorCode == 405) {
				displayErrorMessage(R.string.alert_token_expired);
				startTokenInitializeActivity();
			} else {
				displayErrorMessage(R.string.alert_failed_getting_transaction);
				status = Config.PROGRESS_STOPPED;
			}
		};
	};
	
	private void hideProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	private void initializeDataFromSharedPreference() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		token = prefs.getString(Config.TOKEN, "");
		phoneNumber = prefs.getString(Config.PHONE_NUMBER, "");

		if (token.contentEquals("")) {
			Log.e(TAG, "token not saved from previous activity");
			AlertDialog.Builder alertTokenNotRecieved = new AlertDialog.Builder(
					this);
			alertTokenNotRecieved.setTitle(this.getString(R.string.alert));
			alertTokenNotRecieved
					.setMessage(getString(R.string.alert_token_not_saved));
			alertTokenNotRecieved.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

			
				@Override
						public void onClick(DialogInterface dialog, int which) {
							startTokenInitializeActivity();
						}
					});
		}
	}
	
	
	private void startTokenInitializeActivity() {
		Intent tokenInitialize = new Intent(TransactionActivity.this, TokenInitializeActivity.class);
		finish();
		startActivity(tokenInitialize);
	}
	
	private void displayErrorMessage(int message) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				TransactionActivity.this);
		alertDialog.setTitle(getString(R.string.alert));
		alertDialog.setMessage(getString(message));
		alertDialog.setPositiveButton(getString(R.string.okay),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alertDialog.show();
	}
	
	private void getTransactionDetails() {
		if (isNetworkAvailable()) {
			Intent getBalanceIntent = new Intent(TransactionActivity.this, TransactionService.class);
			Messenger resultMessenger = new Messenger(
					serviceResultHandler);
			Messenger progressMessenger = new Messenger(
					progressHandler);
			Bundle bundle = new Bundle();
			bundle.putString(Config.PHONE_NUMBER, phoneNumber);
			bundle.putString(Config.TOKEN, token);
			try {
				Log.w(TAG, "inside try");
				getBalanceIntent.putExtras(bundle);
				getBalanceIntent.putExtra(Config.RESULT_MESSENGER,
						resultMessenger);
				getBalanceIntent.putExtra(Config.PROGRESS_MESSENGER,
						progressMessenger);
				startService(getBalanceIntent);
			} catch (SecurityException e) {
				Log.w(TAG, "Unable to start get transactions service: "
						+ e.toString());
			}
		}
	}
	
	private ArrayList<Transaction> parseJsonList(String responseString) {
		ArrayList<Transaction> tList = new ArrayList<Transaction>();
		try {
			JSONArray topUpTransactionArray = new JSONObject(responseString).getJSONArray(TOP_UP_TRANSACTION);
			for (int i = 0; i < topUpTransactionArray.length(); i++) {
				JSONObject obj = topUpTransactionArray.getJSONObject(i);
				Transaction transaction = new Transaction();
				transaction.setRequester(obj.getString("Requester"));
				transaction.setReceiver(obj.getString("Receiver"));
				transaction.setPreviousCredit(obj.getString("CreaditAtTheTimeOfTopup"));
				transaction.setAmount(obj.getString("TopupAmount"));
				transaction.setDate(obj.getString("TopUpDate"));
				transaction.setMethod(Integer.parseInt(obj.getString("TopUpMethod")));
				transaction.setId(obj.getString("Id"));
				tList.add(transaction);
			}			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return tList;
	}
}
